package com.xckj.cycling.service

import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.xckj.cycling.framework.lazyGlobalViewModel
import com.xckj.cycling.utils.ToastUtils
import com.xckj.cycling.viewmodel.PushViewModel

/**
 * 负责接收FCMtoken 和 消息
 */
class FCMPushService : FirebaseMessagingService() {
    override fun onNewToken(token: String) {
        super.onNewToken(token)
        viewModel.uploadToken(token)
    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
    }

    companion object {
        private val viewModel: PushViewModel by lazyGlobalViewModel()

        fun init() {
            val fcm = FirebaseMessaging.getInstance()
            fcm.isAutoInitEnabled = true
            fcm.token.addOnCompleteListener {
                if (it.isSuccessful) {
                    ToastUtils.debug("获取FCM token 成功 ${it.result}")
                    viewModel.uploadToken(it.result)
                } else {
                    ToastUtils.debug("获取FCM token 失败 ${it.exception?.message}")
                }
            }
        }
    }
}